package com.todod.service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.elasticsearch.action.admin.cluster.health.ClusterHealthRequest;
import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.client.indices.GetIndexRequest;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.MatchAllQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.reindex.DeleteByQueryRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSON;
import com.todod.dto.EsBmwdDto;
import com.todod.dto.PublicFileDto;
import com.todod.mapper.PublicCatalogMapper;
import com.todod.mapper.PublicFileMapper;
import com.todod.model.PublicCatalog;
import com.todod.model.User;

import net.logstash.logback.encoder.org.apache.commons.lang.StringUtils;

@Service
@Transactional
public class EsService {
	@Autowired
	private RestHighLevelClient restHighLevelClient;
	@Autowired
	private PublicFileMapper publicFileMapper;
	@Autowired
	public PublicCatalogMapper publicCatalogMapper;
	@Autowired
	private IUserService iUserService;

	public void delete() throws IOException {
		if (restHighLevelClient.indices().exists(new GetIndexRequest("bmwd"), RequestOptions.DEFAULT)) {
			restHighLevelClient.indices().delete(new DeleteIndexRequest("bmwd"), RequestOptions.DEFAULT);
		}
		if (restHighLevelClient.indices().exists(new GetIndexRequest("grwd"), RequestOptions.DEFAULT)) {
			restHighLevelClient.indices().delete(new DeleteIndexRequest("grwd"), RequestOptions.DEFAULT);
		}
	}

	/**
	 * 删除es索引下 所有文档
	 * 
	 * @author hyw
	 * @throws IOException
	 */
	public void deleteAll() throws IOException {
		DeleteByQueryRequest request = new DeleteByQueryRequest("bmwd", "grwd");
		MatchAllQueryBuilder matchAllQuery = QueryBuilders.matchAllQuery();
		System.out.println(matchAllQuery);
		request.setQuery(matchAllQuery);
		restHighLevelClient.deleteByQuery(request, RequestOptions.DEFAULT);
	}

	/**
	 * 删除指定库内容
	 * 
	 * @param code
	 * @throws IOException
	 */
	public void deleteByCode(String code) throws IOException {
		DeleteByQueryRequest request = new DeleteByQueryRequest(code);
		MatchAllQueryBuilder matchAllQuery = QueryBuilders.matchAllQuery();
		request.setQuery(matchAllQuery);
		restHighLevelClient.deleteByQuery(request, RequestOptions.DEFAULT);
	}

	/**
	 * 部门文档索引导入
	 * 
	 * @author hyw
	 * @throws IOException
	 */
	public void synchronization(String flag, Long userId) throws IOException {
		try {
			if (flag.equalsIgnoreCase("M")) {
				deleteByCode("bmwd");
			} else {
				deleteByCode("grwd");
			}
		} catch (IOException e1) {

			e1.printStackTrace();
		}
		// 获取部门文档Dto
		List<PublicFileDto> list = null;
		if (flag.equalsIgnoreCase("M")) {
			list = publicFileMapper.getNewListEs();
		} else {
			list = publicFileMapper.getNewList12(userId);
		}

		String suffix = "png,jpeg,jpg,gif,tif,bmp,webp,ico,pdf,docx,doc,txt,ppt,pptx,xlsx,xls,mp4,mpeg,avi,navi,asf,mov,3gp,wmv,divx,xvid,rm,rmvb,flv,f4v,mp3,flac,wav,flac";

		List<EsBmwdDto> list2 = new ArrayList<>();
		for (PublicFileDto publicFile : list) {
			EsBmwdDto bmwdDto = new EsBmwdDto();

			String gftName = "";
			String level = publicFile.getLevels();
			if (level != null && StringUtils.isNotBlank(level)) {
				String[] levels = level.split(";");

				for (int i = 0; i < levels.length; i++) {
					if (i == 0) {
						PublicCatalog publicCatalog = publicCatalogMapper.selectById(levels[i]);
						gftName = gftName + publicCatalog.getTypeName();
					} else {
						PublicCatalog publicCatalog = publicCatalogMapper.selectById(levels[i]);
						gftName = gftName + "->" + publicCatalog.getTypeName();
					}
				}
			}

//			PublicCatalog publicCatalog = publicCatalogMapper.selectById(publicFile.getGftId());
//			gftName = publicCatalog.getTypeName() + gftName;
//
//			if (publicCatalog.getParentId() != 1l && publicCatalog.getParentId() != null) {
//				PublicCatalog a = new PublicCatalog();
//				Long gftId = publicCatalog.getParentId();
//				a.setId(gftId);
//				List<PublicCatalog> list1 = publicCatalogMapper.selectList(null);
//				for (int i = 0; i < list1.size(); i++) {
//					if (a.getId() != 1l && a.getId() != null) {
//						Optional<PublicCatalog> any = list1.stream().filter((x) -> x.getId().equals(a.getId()))
//								.findAny();
//						if (any.isPresent()) {
//							gftName = any.get().getTypeName() + "->" + gftName;
//							gftId = any.get().getParentId();
//							a.setId(gftId);
//						}
//					}
//				}
//			}

			bmwdDto.setId(publicFile.getId());
			bmwdDto.setDepartmentId(publicFile.getDepartmentId());
			bmwdDto.setGftId(publicFile.getGftId());
			bmwdDto.setGftName(gftName);
			bmwdDto.setFileName(publicFile.getOriginalName());
			bmwdDto.setFileLabel(publicFile.getFileLabel());

			if (!publicFile.getSuffix().equalsIgnoreCase("文件夹")) {
				if (suffix.indexOf(publicFile.getSuffix()) < 0) {
					bmwdDto.setSuffix("其他");
				} else {
					bmwdDto.setSuffix(publicFile.getSuffix());
				}
			} else {
				bmwdDto.setSuffix("文件夹");
			}

			bmwdDto.setFileSize(publicFile.getFileSize());
			bmwdDto.setType(publicFile.getType());
			bmwdDto.setState(publicFile.getState());
			bmwdDto.setSortNum(publicFile.getSortNum());
			bmwdDto.setPaixu(publicFile.getPaixu());
			bmwdDto.setCreatetimeTi(publicFile.getCreatetimeTi());
			bmwdDto.setCreateuserId(publicFile.getCreateuserId());

			User user = iUserService.getById(publicFile.getCreateuserId());
			bmwdDto.setUserName(user.getNickName());

			int result01 = bmwdDto.getSuffix().indexOf("docx");
			int result02 = bmwdDto.getSuffix().indexOf("doc");
			int result03 = bmwdDto.getSuffix().indexOf("xlsx");
			int result04 = bmwdDto.getSuffix().indexOf("xls");
			int result05 = bmwdDto.getSuffix().indexOf("txt");
			int result06 = bmwdDto.getSuffix().indexOf("ppt");
			int result07 = bmwdDto.getSuffix().indexOf("pptx");

			if (result01 != -1 || result02 != -1 || result03 != -1 || result04 != -1 || result05 != -1 || result06 != -1
					|| result07 != -1) {
				bmwdDto.setUrl(publicFile.getYulanPath());
			} else {
				bmwdDto.setUrl(publicFile.getAbstractPath());
			}

			bmwdDto.setContent(publicFile.getContent());
			bmwdDto.setDownloads(0);
			bmwdDto.setViews(0);
			list2.add(bmwdDto);
		}

		int size = list2.size();
		// 循环次数
		int num = size / 1000;
		// 取余
		int remainder = size % 1000;
		if (remainder != 0) {
			num += 1;
		}
		for (int i = 0; i < num; i++) {
			BulkRequest bulkRequest = new BulkRequest();
			for (int j = 0 + (1000 * i); j < 1000 + (1000 * i); j++) {
				if (j >= size) {
					break;
				}

				if (flag.equalsIgnoreCase("M")) {
					bulkRequest.add(new IndexRequest("bmwd").id(String.valueOf(list2.get(j).getId()))
							.source(JSON.toJSONString(list2.get(j)), XContentType.JSON));
				} else {
					bulkRequest.add(new IndexRequest("grwd").id(String.valueOf(list2.get(j).getId()))
							.source(JSON.toJSONString(list2.get(j)), XContentType.JSON));
				}

				System.out.println(j);
			}

			try {
				BulkResponse bulkResponse = restHighLevelClient.bulk(bulkRequest, RequestOptions.DEFAULT);
				if (bulkResponse.hasFailures()) {
					System.out.println(bulkResponse.buildFailureMessage());
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	/**
	 * 刷新流
	 * 
	 * @throws IOException
	 */
	public void esRefresh() throws IOException {
		ClusterHealthRequest request = new ClusterHealthRequest();
		restHighLevelClient.cluster().health(request, RequestOptions.DEFAULT);

	}
}
